package hu.elte.tudaskezelo.dbpedialike.ws;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.util.Log;

public class DomParser{

	public List<NameValuePair> parse(InputStream is){

		String nodeName = "";
		String nodeValue = "";
		List<NameValuePair> retPairs = new ArrayList<NameValuePair>();
		
		try {
		
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new InputSource(is));
			doc.getDocumentElement().normalize();			
			NodeList nodeList = doc.getElementsByTagName("binding");
			//Log.d("parser:nodeList_length",  "" + nodeList.getLength());
			
			for (int i = 0; i < nodeList.getLength(); i++) {
				
				Node node = nodeList.item(i);
				//Log.d("parser_nodelist",  nodeList.item(i).getAttributes().item(0).getNodeValue());
				nodeName = nodeList.item(i).getAttributes().item(0).getNodeValue();
				Element fstElmnt = (Element) node;	
				NodeList nameList = fstElmnt.getChildNodes();
								
				for (int j = 0; j < nameList.getLength(); j++){
					
					Element nameElement = (Element) nameList.item(j);
					NodeList theElement = nameElement.getChildNodes();	

					//Log.d("parser",  theElement.item(0).getNodeValue());
					nodeValue = theElement.item(0).getNodeValue();
					retPairs.add(new BasicNameValuePair(nodeName, nodeValue));
				}
			}
		} catch (Exception e) {
			Log.d("DomParser", "XML Parsing Excpetion = " + e);
		}
		
		return retPairs;
	}
}
